// stores/goods.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface GoodsItem {
	id: number;
	thumbnail: string;
	name: string;
	price: number;
	stock: number;
	status: number; // 1: 上架, 0: 下架
	category: string;
}

export const useGoodsStore = defineStore('goods', () => {
	const goodsList = ref<GoodsItem[]>([]);
	const loading = ref(false);
	const searchKeyword = ref('');

	const filterForm = ref({
		category: '',
		status: '',
		priceRange: [0, 1000],
	});

	const categories = ref([
		{ value: '', label: '全部分类' },
		{ value: '水果', label: '水果' },
		{ value: '蔬菜', label: '蔬菜' },
		{ value: '数码', label: '数码' },
	]);

	const statusOptions = ref([
		{ value: '', label: '全部状态' },
		{ value: '1', label: '上架' },
		{ value: '0', label: '下架' },
	]);

	const getFilteredGoods = computed(() => {
		return goodsList.value.filter((item) => {
			// 搜索过滤
			const matchSearch = !searchKeyword.value || item.name.includes(searchKeyword.value) || item.id.toString().includes(searchKeyword.value);

			// 分类过滤
			const matchCategory = !filterForm.value.category || item.category === filterForm.value.category;

			// 状态过滤
			const matchStatus = !filterForm.value.status || item.status.toString() === filterForm.value.status;

			// 价格范围过滤
			const matchPrice = item.price >= filterForm.value.priceRange[0] && item.price <= filterForm.value.priceRange[1];

			return matchSearch && matchCategory && matchStatus && matchPrice;
		});
	});

	const initGoodsList = (data: GoodsItem[]) => {
		goodsList.value = data;
	};

	const updateSearchKeyword = (keyword: string) => {
		searchKeyword.value = keyword;
	};

	const deleteGoods = (id: number) => {
		goodsList.value = goodsList.value.filter((item) => item.id !== id);
	};

	const showFilter = ref(false);

	const applyFilter = () => {
		showFilter.value = false;
	};

	const resetFilter = () => {
		filterForm.value = {
			category: '',
			status: '',
			priceRange: [0, 1000],
		};
		showFilter.value = false;
	};

	return {
		goodsList,
		loading,
		searchKeyword,
		filterForm,
		categories,
		statusOptions,
		getFilteredGoods,
		initGoodsList,
		updateSearchKeyword,
		deleteGoods,
		showFilter,
		applyFilter,
		resetFilter,
	};
});
